import { useDispatch } from 'react-redux'
import { addMessage, addSystemMessage, setLoading } from '../store/messageSlice'
import { XStream } from '@ant-design/x'
import { useMessageList } from './useMessageList'
import { message } from 'antd'

export function useSubmitMsg() {
  const dispatch = useDispatch()
  const { selectedModel, currentChatList } = useMessageList()

  return async (value: string) => {
    dispatch(setLoading(true))
    // 添加用户消息到 store
    dispatch(addMessage(value))
    try {
      // 请求node接口
      const response = await fetch(`http://localhost:3000/api/chat`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          message: value,
          model: selectedModel,
          messageList: currentChatList || []
        })
      })
      // 获取响应，使用封装好的XStream处理流数据
      if (response.body) {
        let isFirst = true
        for await (const chunk of XStream({ readableStream: response.body })) {
          const parseChunk = JSON.parse(chunk.data)
          const { content, done, reasoning_content } = parseChunk

          if (isFirst) {
            // 第一次流数据，新建一条AI消息
            dispatch(
              addSystemMessage({
                reasoning_content: reasoning_content || '',
                content: content || ''
              })
            )
            isFirst = false
          } else {
            // 后续流数据，只追加新内容
            dispatch(
              addSystemMessage({
                reasoning_content: reasoning_content || '',
                content: content || ''
              })
            )
          }

          if (done) {
            dispatch(setLoading(false))
          }
        }
      }
    } catch (error) {
      console.log(error)

      message.error('请求失败，请稍后重试 ' + error)
      dispatch(setLoading(false))
    }
  }
}
